package com.health.life;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.myjson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.health.life.enty.CookBook;
import com.health.life.enty.CookBookResp;
import com.health.life.utils.ViewHolder;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tukela on 2015/7/6.
 */
public class CookListActivity extends MyBaseActivity implements AdapterView.OnItemClickListener {
    private PullToRefreshGridView gridview;
    private com.google.myjson.Gson gson=new Gson();
    private int pageSize=20;
    private int pageIndex=0;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            cancelPressDialog();
            switch (msg.what)
            {
                case 0x200:
                    String receiveJson= (String) msg.obj;
                    CookBookResp response = gson.fromJson(receiveJson, CookBookResp.class);
                    List<CookBook> temList=response.getYi18();
                    if (temList!=null&&temList.size()>0)
                    {
                        bookList.addAll(temList);
                        mAdapter.notifyDataSetChanged();
                        for (CookBook cookBook : temList) {
                            cookBook.setFid(id);
                            cookBook.setImg(App.BASE_IMG_URL+cookBook.getImg());
                        }
                        try {
                            dbUtils.saveOrUpdateAll(temList);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }

                    break;
                case 0x201:
                    try {
                        List<CookBook> temList2=dbUtils.findAll(Selector.from(CookBook.class).where("fid", "=", id).orderBy("id").limit(pageSize).offset(pageSize * pageIndex));//
                        if (temList2!=null&&temList2.size()>0)
                        {
                            bookList.addAll(temList2);
                            mAdapter.notifyDataSetChanged();

                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
            }
            gridview.onRefreshComplete();
            RefreshPageIndex();
        }
    };
    private DbUtils dbUtils;
    private String id="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cooklist);
        id=getIntent().getStringExtra("ID");
        dbUtils=DbUtils.create(this);
        gridview =(PullToRefreshGridView)findViewById(R.id.gridview);
        gridview.setAdapter(mAdapter);
        gridview.setMode(PullToRefreshBase.Mode.BOTH);
        gridview.setOnRefreshListener(myListener);
        gridview.setOnItemClickListener(this);
        initData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long lid) {
        Intent intent=new Intent(this,ShowDetailActivity.class);
        intent.putExtra("FID",id);
        intent.putExtra("ID",bookList.get(position).getId());
        startActivity(intent);
    }


    public void RefreshPageIndex(){
        if (bookList.size()%pageSize==0)
        {
            pageIndex=bookList.size()/pageSize;
        }else {
            pageIndex=(bookList.size()/pageSize)+1;
        }
    }


    private void initData() {

        showPressDialog();
        new Thread(){
            @Override
            public void run() {
                super.run();
                HttpUtils httpUtils=new HttpUtils();
                RequestParams params=new RequestParams();
                params.addBodyParameter("page",""+(pageIndex+1));
                params.addBodyParameter("limit",""+20);
                params.addBodyParameter("type","id");//排序方式 id：最新时间，count：访问最多，默认是id，按最新时间。
                params.addBodyParameter("id",id);
                httpUtils.send(HttpRequest.HttpMethod.POST,
                        App.List_URL,
                        params,
                        new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                Message message=handler.obtainMessage();
                                message.what=0x200;
                                message.obj=responseInfo.result;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onFailure(HttpException e, String s) {
                                handler.sendEmptyMessage(0x201);
                            }
                        });
            }
        }.start();
    }

    private List<CookBook> bookList=new ArrayList<>(0);
    BaseAdapter mAdapter =new  BaseAdapter(){

        @Override
        public int getCount() {
            return bookList.size()>0?bookList.size():0;
        }

        @Override
        public Object getItem(int position) {
            return bookList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CookBook cookList=bookList.get(position);
            if (convertView==null){
                convertView= LayoutInflater.from(CookListActivity.this).inflate(R.layout.show_item, null);
            }
            ImageView imageView= ViewHolder.get(convertView, R.id.image);
            TextView textView= ViewHolder.get(convertView, R.id.tv);
            ImageLoader.getInstance().displayImage(cookList.getImg().replace(" ",""), imageView);
            //    new DownLoadImage(imageView).execute(cookList.getImg());
            textView.setText(cookList.getName());
            return convertView;
        }
    };

    PullToRefreshBase.OnRefreshListener2 myListener =new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {
            handler.sendEmptyMessage(0x203);
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            initData();
        }
    };

}
